﻿namespace BM.Tools.WebControls.MForm.Generator
{
    using System.Xml.Schema;

    using BM.Tools.Xml.Schema;

    /// <summary>
    /// A factory class that created <see cref="FormVisited"/> objects
    /// </summary>
    public class FormVisitedFactory : VisitedFactory<FormVisited>
    {
        /// <summary>
        /// Creates appropriate FormVisited objects based on the xml schema object
        /// </summary>
        /// <param name="parent">
        /// the parent visited object
        /// </param>
        /// <param name="xso">
        /// the xml schema object
        /// </param>
        /// <param name="visitor">
        /// the visitor object
        /// </param>
        /// <returns>
        /// the visited object
        /// </returns>
        public override FormVisited Create(FormVisited parent, XmlSchemaObject xso, Visitor<FormVisited> visitor)
        {
            var builder = visitor as FormBuilder;
            var choice = xso as XmlSchemaChoice;
            if (choice != null)
            {
                return new FormChoice(builder, parent, choice);
            }

            var element = xso as XmlSchemaElement;
            if (element != null)
            {
                var complexType = element.ElementSchemaType as XmlSchemaComplexType;
                if (element.IsAbstract || (complexType != null && complexType.IsAbstract))
                {
                    return new FormSubstitution(builder, parent, element);
                }

                if (element.RefName.IsEmpty)
                {
                    return new FormElement(builder, parent, element);
                }
            }

            XmlSchemaAttribute xsa = xso as XmlSchemaAttribute;
            if (xsa != null)
            {
                if (xsa.RefName.IsEmpty)
                {
                    return new FormAttribute(builder, parent, xsa);
                }
            }

            return new FormVisited(builder, parent, xso);
        }
    }
}
